package com.tbit.uqbike.service.business.impl;


import cn.hutool.core.util.StrUtil;
import com.tbit.common.config.OssDefaultConfig;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Account;
import com.tbit.uqbike.object.pojo.Image;
import com.tbit.uqbike.object.pojo.OssConfig;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.ImageService;
import com.tbit.uqbike.service.business.OssConfigService;
import com.tbit.uqbike.webmanager.dao.huge.ImageDao;
import com.tbit.uqbike.webmanager.util.aliyun.OssFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;


@Service("imageService")
public class ImageServiceImpl implements ImageService {

    @Autowired
    private OssConfigService ossConfigService;

    @Autowired
    private OssDefaultConfig ossDefaultConfig;

    @Autowired
    private AccountService accountService;

    @Autowired
    private ImageDao imageDao;

    @Override
    public Image getByImageId(String imageId) {
        return imageDao.getByImageId(imageId);
    }

    @Override
    public void setImage(Image image) {
        imageDao.insert(image);
    }

    @Override
    public void delByImageId(String imageId) {
        imageDao.del(imageId);
    }

    @Override
    public String uploadImage(Integer accountId, MultipartFile file, String bucketName){
        try {
            InputStream inputStream = file.getInputStream();
            // 阿里云配置
            OssConfig ossConfig = new OssConfig(ossDefaultConfig.getEndpoint(),
                    ossDefaultConfig.getAccessKeyId(),
                    ossDefaultConfig.getAccessKeySecret(), StrUtil.isBlank(bucketName) ? "gx-res" : bucketName);
            Account account = accountService.getAgentId(accountId);
            // 查询是已否存在配置信息
            OssConfig ossConfigDB = ossConfigService.getByAccountId(account.getParentId());
            if (ossConfigDB != null) {
                ossConfig = ossConfigDB;
            }
            // 添加图片
            String imageId = UUID.randomUUID().toString();
            // 上传阿里云
            String url = OssFileUtils.uploadByAliYun(inputStream, ossConfig, imageId, file.getContentType(), OssFileUtils.IMAGE);
            Image image = new Image();
            image.setImageId(url);
            image.setCreateTime(new Date());
            image.setImageType(file.getContentType());
            image.setImageContent(file.getBytes());
            // 插入
            this.setImage(image);
            return url;
        } catch (Exception e) {
            throw new BaseException("图片格式异常，请检查图片属性");
        }
    }

}  